package com.qing.common.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author guoqf
 */
public class ServerSocketTest {

    public static void main(String[] args) {

        try {

            ServerSocketChannel serverChannel = ServerSocketChannel.open();
            Selector selector = Selector.open();
            try {
                serverChannel.bind(new InetSocketAddress(8888));
                serverChannel.configureBlocking(false);

                serverChannel.register(selector, SelectionKey.OP_ACCEPT);


                while (true) {

                    selector.select();
                    Set<SelectionKey> keys = selector.selectedKeys();
                    if (keys != null && !keys.isEmpty()) {
                        Iterator<SelectionKey> iterator = keys.iterator();
                        while (iterator.hasNext()) {
                            SelectionKey k = iterator.next();
                            if (k.isAcceptable()) {
                                ServerSocketChannel channel = (ServerSocketChannel) k.channel();
                                SocketChannel socketChannel = channel.accept();
                                if (socketChannel != null) {
                                    socketChannel.configureBlocking(false);
                                    socketChannel.register(selector, SelectionKey.OP_READ);
                                    System.out.println("接收客户端连接: " + socketChannel);
                                }
                            } else if (k.isReadable()) {
                                SocketChannel channel = (SocketChannel) k.channel();
                                ByteBuffer buf = ByteBuffer.allocate(256);
                                int read = channel.read(buf);
                                if (read > 0) {

                                    byte[] array = buf.array();
                                    System.out.println("接收客户端消息: " + new String(array));
                                } else if (read == -1) {
                                    System.out.println("客户端断开连接: " + channel);
                                    channel.close();
                                }
                            }

                            iterator.remove();
                        }
                    }


                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException | RuntimeException e) {
            throw new RuntimeException(e);
        }

    }
}
